﻿using RXY_Mall.Api.Common;
using RXY_Mall.Api.Models;
using RXY_Mall.Core;
using AliyunSmsSDK;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using WebApi.OutputCache.V2;
using RXY_Mall.Services.User;

namespace RXY_Mall.Api.Controllers
{
    /// <summary>
    /// 基础接口
    /// </summary>
    [RoutePrefix("Base")]
    [ApiSecurityFilter]
    public partial class BaseController : BaseApiController
    {
        private RXY_MallContext db;
        private UserService userService;

        public BaseController()
        {
            db = new RXY_MallContext();
            userService = new UserService();
        }

        /// <summary>
        /// 通过时间判断业务是否可用
        /// </summary>
        /// <returns></returns>
        private Response<string> isFuctionByDate()
        {
            Response<string> result = new Response<string>();
            result.code = 0;

            //工作日 周一至周五
            DateTime dt = DateTime.Now;
            var nonWorkingDays = AppConfig.NonWorkingDays.Split(',');
            if (nonWorkingDays.Contains(dt.DayOfWeek.ToString()))
            {
                result.msg = "非工作日（周一至周五）不受理该业务";
                return result;
            }

            //时间段
            DateTime startWorkingTime = DateTime.Parse(DateTime.Now.ToString(string.Format("yyyy-MM-dd {0}", AppConfig.StartWorkingTime)));
            DateTime endWorkingTime = DateTime.Parse(DateTime.Now.ToString(string.Format("yyyy-MM-dd {0}", AppConfig.EndWorkingTime)));
            if (!(DateTime.Compare(dt, startWorkingTime) >= 0 && DateTime.Compare(dt, endWorkingTime) < 0))
            {
                result.msg = string.Format("非工作时间（{0}-{1}）不受理该业务", AppConfig.StartWorkingTime, AppConfig.EndWorkingTime);
                return result;
            }

            if (!string.IsNullOrEmpty(AppConfig.Holidays))
            {
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                //节假日
                var holidays = AppConfig.Holidays.Split(',');
                if (holidays.Contains(today))
                {
                    result.msg = "法定假日不受理该业务";
                    return result;
                }
            }

            result.code = 1;
            return result;
        }

        /// <summary>
        /// 验证支付密码
        /// </summary>
        /// <param name="password">支付密码</param>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        private Response<string> IsPassword(string password, int user_id)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            string error = "";
            if (!userService.IsPassword(user_id, password, 0, out error))
            {
                result.msg = error;
                return result;
            }
            result.code = 1;
            return result;
        }

        /// <summary>
        /// 检查分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        private void CheckPage(ref int pageIndex, ref int pageSize)
        {
            if (pageIndex <= 0)
                pageIndex = 1;
            if (pageSize <= 0)
                pageSize = 15;
            if (pageSize > 100)
                pageSize = 100;
        }

        /// <summary>
        /// 检查手机号是否注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("CheckMobileIsExist")]
        public async Task<Response<bool>> CheckMobileIsExist(SendSMSByRegisterInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                if (!Validator.IsMobile(input.mobile))
                {
                    result.msg = "手机号码格式不正确";
                    return result;
                }

                var userService = new UserService();
                result.code = 1;
                var flag = await userService.ExistUserByMobile(input.mobile); ;
                if (flag)
                {
                    result.msg = "该手机号已注册";
                    return result;
                }


                result.data = true;

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        #region 短信
        /// <summary>
        /// 发送忘记支付密码短信
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByForgetPayPassword")]
        public async Task<Response<bool>> SendSMSByForgetPayPassword(BaseInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 1;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "用户不存在！";
                    return result;
                }
                SendSMSInput smsInput = new SendSMSInput()
                {
                    mobile = user.name,
                    sms_type = SMSType.ForgetPayPassword,
                    user_id = user.id
                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送快速登录短信
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByQuickLogin")]
        public async Task<Response<bool>> SendSMSByQuickLogin(SendSMSByRegisterInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 1;
            result.msg = "";
            result.data = false;

            try
            {
                gw_user user = await db.gw_users.FirstOrDefaultAsync(u => u.name == input.mobile);
                if (user == null)
                {
                    return await SendSMSByRegister(new SendSMSByRegisterInput() { mobile = input.mobile });
                    //result.msg = "用户不存在";
                    //return result;
                }

                SendSMSInput smsInput = new SendSMSInput()
                {
                    mobile = user.name,
                    sms_type = SMSType.QuickLogin,
                    user_id = user.id
                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送绑定登录短信
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByBindingLogin")]
        public async Task<Response<bool>> SendSMSByBindingLogin(SendSMSByRegisterInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                gw_user user = await db.gw_users.FirstOrDefaultAsync(u => u.name == input.mobile);
                SendSMSInput smsInput;
                if (user == null)
                {
                    //注册
                    smsInput = new SendSMSInput()
                    {
                        mobile = input.mobile,
                        sms_type = SMSType.Register,
                    };
                }
                else
                {
                    //绑定
                    smsInput = new SendSMSInput()
                    {
                        mobile = user.name,
                        sms_type = SMSType.Binding,
                        user_id = user.id
                    };
                }

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送忘记登录密码短信-找回密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByForgetLoginPassword")]
        public async Task<Response<bool>> SendSMSByForgetLoginPassword(SendSMSByRegisterInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                gw_user user;
                if (Validator.IsMobile(input.mobile))
                {
                    var users = await db.gw_users.Where(u => u.name == input.mobile).ToListAsync();
                    if (users.Count > 1)
                    {
                        result.msg = "请使用用户名登录";
                        return result;
                    }
                    user = users.FirstOrDefault();
                }
                else
                {
                    user = await db.gw_users.FirstOrDefaultAsync(u => u.name == input.mobile);
                }

                if (user == null)
                {
                    result.msg = "用户不存在";
                    return result;
                }

                SendSMSInput smsInput = new SendSMSInput()
                {
                    mobile = user.name,
                    sms_type = SMSType.ForgetLoginPassword,
                    user_id = user.id

                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送用户注册短信
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByRegister")]
        public async Task<Response<bool>> SendSMSByRegister(SendSMSByRegisterInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                if (!Validator.IsMobile(input.mobile))
                {
                    result.msg = "手机号码格式不正确";
                    return result;
                }

                var userService = new UserService();
                var flag = await userService.ExistUserByMobile(input.mobile); ;
                if (flag)
                {
                    result.msg = "该手机号已注册";
                    return result;
                }

                SendSMSInput smsInput = new SendSMSInput()
                {

                    mobile = input.mobile,
                    sms_type = SMSType.Register,
                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送更换手机短信-第一步
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByUpdateMobile")]
        public async Task<Response<bool>> SendSMSByUpdateMobile(BaseInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "用户不存在！";
                    return result;
                }
                SendSMSInput smsInput = new SendSMSInput()
                {

                    mobile = user.name,
                    sms_type = SMSType.UpdateMobile,
                    user_id = user.id
                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送更换新手机短信-第二步
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByUpdateNewMobile")]
        public async Task<Response<bool>> SendSMSByUpdateNewMobile(SendSMSByUpdateNewMobileInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                if (!Validator.IsMobile(input.mobile))
                {
                    result.msg = "手机号码格式不正确";
                    return result;
                }

                var userService = new UserService();
                var flag = await userService.ExistUserByMobile(input.mobile); ;
                if (flag)
                {
                    result.msg = "该手机号已注册";
                    return result;
                }

                SendSMSInput smsInput = new SendSMSInput()
                {

                    mobile = input.mobile,
                    sms_type = SMSType.UpdateNewMobile,
                    user_id = input.user_id,
                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送添加登录密码短信
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByAddLoginPassword")]
        public async Task<Response<bool>> SendSMSByAddLoginPassword(BaseInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "用户不存在！";
                    return result;
                }
                SendSMSInput smsInput = new SendSMSInput()
                {

                    mobile = user.name,
                    sms_type = SMSType.AddLoginPassword,
                    user_id = user.id
                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送添加支付密码短信
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSMSByAddPayPassword")]
        public async Task<Response<bool>> SendSMSByAddPayPassword(BaseInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "用户不存在！";
                    return result;
                }
                SendSMSInput smsInput = new SendSMSInput()
                {

                    mobile = user.name,
                    sms_type = SMSType.AddPayPassword,
                    user_id = user.id
                };

                result = await SendSMS(smsInput);
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <returns></returns>
        private async Task<Response<bool>> SendSMS(SendSMSInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            try
            {

                if (string.IsNullOrEmpty(input.mobile)) { result.msg = "手机号为空"; return result; }
                if (!Validator.IsMobile(input.mobile)) { result.msg = "手机号格式不正确"; return result; }

                //十分钟内是否发送了10次短信
                DateTime dtNow = DateTime.Now.AddMinutes(-10);
                var count = await db.gw_base_smses.CountAsync(g => g.mobile == input.mobile && g.add_time >= dtNow);
                if (count > 10) { result.msg = "系统检测到您恶意操作,请稍候再试"; return result; }

                string code = Utils.Number(6);
                string error;
                bool flag = AliyunSmSHelper.SendSMS(input.mobile, code, out error);
                if (flag)
                {
                    gw_base_sms model = new gw_base_sms();
                    if (input.user_id != 0)
                    {
                        model.user_id = input.user_id;
                    }
                    model.mobile = input.mobile;
                    model.type = (byte)input.sms_type;
                    model.code = code;
                    model.count = 0;
                    model.status = 0;
                    model.ip = DcRequest.GetIP();
                    model.eff_time = DateTime.Now.AddMinutes(20);
                    model.add_time = DateTime.Now;

                    db.gw_base_smses.Add(model);
                    await db.SaveChangesAsync();

                    if (model.id > 0)
                    {
                        result.code = 1;
                        result.msg = "发送成功,请注意收到的短信";
                        result.data = true;
                    }
                    else
                    {
                        result.msg = "发送失败";
                    }
                }
                else
                {
                    LogHelper.WriteLog("短信异常:" + error);
                    error = "您操作过于频繁,请稍候再试。";
                    result.msg = error;
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;

        }

        #endregion

        #region 通知
        ///// <summary>
        ///// 获取系统通知
        ///// </summary>
        //[HttpGet]
        //[Route("GetNotices")]
        //public async Task<Response<List<NoticeOutput>>> GetNotices(int user_id)
        //{
        //    Response<List<NoticeOutput>> result = new Response<List<NoticeOutput>>();

        //    try
        //    {
        //        result.code = 1;
        //        var notices = await db.gw_notices.Where(n => n.status == 1).OrderByDescending(n => n.add_time).ToListAsync();
        //        List<NoticeOutput> output = new List<NoticeOutput>();
        //        if (notices != null && notices.Count > 0)
        //        {
        //            foreach (var item in notices)
        //            {
        //                NoticeOutput model = new NoticeOutput()
        //                {
        //                    noticeId = item.id,
        //                    addTime = (DateTime)item.add_time,
        //                    gotoUrl = item.goto_url,
        //                    isLook = false,
        //                    title = item.title
        //                };
        //                output.Add(model);
        //            }
        //        }

        //        var deliver = await db.gw_deliver_infos.FirstOrDefaultAsync(d => d.status == 1 && d.start_time <= DateTime.Now && d.end_time > DateTime.Now);
        //        if (deliver != null)
        //        {
        //            NoticeOutput model = new NoticeOutput()
        //            {
        //                noticeId = 0,
        //                addTime = DateTime.Now,
        //                gotoUrl = "",
        //                isLook = false,
        //                title = string.Format("本期科恩币发行量:{0},剩余:{1}", deliver.target_coins.ToString("N0"), deliver.now_coins.ToString("N0")),
        //            };
        //            output.Add(model);
        //        }

        //        result.data = output;
        //        result.code = 1;
        //    }
        //    catch (Exception ex)
        //    {
        //        result.code = 2;
        //        result.msg = ex.Message;
        //        LogHelper.WriteLog(ex);
        //    }
        //    return result;
        //}
        #endregion

        #region 上传文件
        /// <summary>
        /// 批量上传图片
        /// </summary>
        /// <param name="input">type:1-商品,2-文件,3-身份证,4-新闻,5-头像,6-评价,7-售后,8-其他</param>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadImages")]
        public async Task<Response<List<string>>> UploadImages(FileInput input)
        {
            Response<List<string>> result = new Response<List<string>>();
            try
            {

                var user = await db.gw_users.FindAsync(input.user_id);

                if (user == null || user.id == 0)
                {
                    result.code = 0;
                    result.msg = "用户不存在";
                    return result;
                }

                if (input.files == null || input.files.Count == 0)
                {
                    result.code = 0;
                    result.msg = "没有上传的文件";
                    return result;
                }

                string strType = "";
                //类型：1-商品,2-文件,3-身份证,4-新闻,5-其他
                switch (input.type)
                {
                    case 1:
                        strType = "goods";
                        break;
                    case 2:
                        strType = "file";
                        break;
                    case 3:
                        strType = "id";
                        break;
                    case 4:
                        strType = "news";
                        break;
                    case 5:
                        strType = "avatar";
                        break;
                    default:
                        strType = "other";
                        break;
                }

                string path = string.Format("/UploadFiles/{0}/{1}/", strType, DateTime.Now.ToString("yyMM"));
                string abtPath = HttpContext.Current.Server.MapPath(path);
                FileHelper.CreateDirectory(abtPath);

                List<string> urllst = new List<string>();
                List<gw_base_file> list = new List<gw_base_file>();
                foreach (var file in input.files)
                {
                    if (string.IsNullOrEmpty(file.base64))
                    {
                        result.code = 0;
                        result.msg = "没有选择要上传的图片";
                        return result;
                    }


                    string fileName = "";
                    string filePath = "";

                    HttpRequest request = HttpContext.Current.Request;
                    //保存图象
                    fileName = string.Format("{0}.{1}", System.Guid.NewGuid().ToString("N"), file.ext);
                    filePath = string.Format("http://{0}{1}{2}", request.Url.Authority, path, fileName);

                    byte[] imgByte = Convert.FromBase64String(file.base64);

                    using (MemoryStream ms = new MemoryStream(imgByte))
                    {
                        using (Image image = System.Drawing.Image.FromStream(ms))
                        {
                            image.Save(abtPath + "\\" + fileName);
                            urllst.Add(filePath);
                        }
                    }

                    gw_base_file model = new gw_base_file()
                    {
                        add_time = DateTime.Now,
                        deleted = false,
                        ext = file.ext,
                        length = file.base64.Length,
                        name = file.name,
                        temp = true,
                        type = input.type,
                        url = filePath,
                        user_id = input.user_id,
                    };
                    list.Add(model);
                }

                db.gw_base_files.AddRange(list);

                await db.SaveChangesAsync();

                result.data = urllst;
                result.code = 1;
                result.msg = "上传成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
                return result;
            }
            return result;
        }

        /// <summary>
        /// 单个上传图片
        /// </summary>
        /// <param name="input">type:1-商品,2-文件,3-身份证,4-新闻,5-头像,6-评价,7-售后,8-其他</param>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadSingleImage")]
        public async Task<Response<string>> UploadSingleImage(FileSingleInput input)
        {
            Response<string> result = new Response<string>();
            try
            {
                if (input == null || input.user_id == 0)
                {
                    result.code = 0;
                    result.msg = "参数错误";
                    return result;
                }
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null || user.id == 0)
                {
                    result.code = 0;
                    result.msg = "用户不存在";
                    return result;
                }

                string strType = "";
                //类型：1-商品,2-文件,3-身份证,4-新闻,5-头像,6-其他
                switch (input.type)
                {
                    case 1:
                        strType = "goods";
                        break;
                    case 2:
                        strType = "file";
                        break;
                    case 3:
                        strType = "id";
                        break;
                    case 4:
                        strType = "news";
                        break;
                    case 5:
                        strType = "avatar";
                        break;
                    default:
                        strType = "other";
                        break;
                }

                string path = string.Format("/UploadFiles/{0}/{1}/", strType, DateTime.Now.ToString("yyMM"));
                string abtPath = HttpContext.Current.Server.MapPath(path);
                FileHelper.CreateDirectory(abtPath);

                List<string> urllst = new List<string>();

                if (string.IsNullOrEmpty(input.base64))
                {
                    result.code = 0;
                    result.msg = "没有选择要上传的图片";
                    return result;
                }


                string fileName = "";
                string filePath = "";

                HttpRequest request = HttpContext.Current.Request;
                //保存图象

                fileName = string.Format("{0}.{1}", System.Guid.NewGuid().ToString("N"), input.ext);
                filePath = string.Format("http://{0}{1}{2}", request.Url.Authority, path, fileName);

                byte[] imgByte = Convert.FromBase64String(input.base64);

                using (MemoryStream ms = new MemoryStream(imgByte))
                {
                    using (Image image = System.Drawing.Image.FromStream(ms))
                    {
                        image.Save(abtPath + "\\" + fileName);
                    }
                }

                gw_base_file model = new gw_base_file()
                {
                    add_time = DateTime.Now,
                    deleted = false,
                    ext = input.ext,
                    length = input.base64.Length,
                    name = input.name,
                    temp = true,
                    type = input.type,
                    url = filePath,
                    user_id = input.user_id,
                };

                db.gw_base_files.Add(model);

                await db.SaveChangesAsync();

                result.data = filePath;
                result.code = 1;
                result.msg = "上传成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
                return result;
            }
            return result;
        }

        #endregion

        #region 地区
        /// <summary>
        /// 获取全部地区
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAreaList")]
        [CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
        public async Task<Response<List<AreaOutput>>> GetAreaList()
        {
            Response<List<AreaOutput>> result = new Response<List<AreaOutput>>();
            result.code = 0;
            try
            {
                List<AreaOutput> output = new List<AreaOutput>();
                var areas = await db.gw_base_areas.OrderBy(a => a.deep).OrderByDescending(a => a.sort).ToListAsync();
                output = GetAreas(areas, 0, 1);
                result.code = 1;
                result.data = output;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.Message;
            }
            return result;
        }

        private static List<AreaOutput> GetAreas(List<gw_base_area> allArea, int? areaParentId, int areaDeep)
        {
            List<AreaOutput> output = new List<AreaOutput>();
            try
            {
                if (areaDeep > 3)
                {
                    return null;
                }
                var areas = allArea.Where(a => a.parent_id == areaParentId && a.deep == areaDeep).ToList();
                foreach (var area in areas)
                {
                    AreaOutput areaOutput = new AreaOutput()
                    {
                        area_id = area.id,
                        deep = area.deep,
                        name = area.name,
                        code = area.code,
                        parent_id = area.parent_id,
                    };
                    int deep = areaDeep + 1;
                    var subAreas = GetAreas(allArea, area.id, deep);
                    if (subAreas != null && subAreas.Count > 0)
                    {
                        areaOutput.sub_areas = subAreas;
                    }
                    output.Add(areaOutput);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return output;
        }

        #endregion

        #region 版本
        /// <summary>
        /// 获取App版本号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetVersion")]
        public async Task<Response<AppVersionOutput>> GetVersion(AppType type)
        {
            Response<AppVersionOutput> result = new Response<AppVersionOutput>();
            try
            {
                var app = await db.gw_base_app_versions.FirstOrDefaultAsync(g => g.type == (byte)type);
                if (app == null)
                {
                    result.code = 0;
                    result.msg = "获取失败！";
                    return result;
                }

                AppVersionOutput output = new AppVersionOutput()
                {
                    remark = app.remark,
                    package_url = app.package,
                    version = app.version,
                };
                result.code = 1;
                result.data = output;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

        #region 物流
        /// <summary>
        /// 获得物流公司
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetLogisticsList")]
        [CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
        public async Task<Response<List<LogisticsOutput>>> GetLogisticsList()
        {
            Response<List<LogisticsOutput>> result = new Response<List<LogisticsOutput>>();
            result.code = 0;
            try
            {
                var output = await db.gw_base_logistics.Where(l => l.status == 1).OrderBy(a => a.sort).Select(l => new LogisticsOutput()
                {
                    logistics_id = l.id,
                    logistics_name = l.name,
                }).ToListAsync();

                result.code = 1;
                result.data = output;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 获得运费
        /// </summary>
        /// <param name="freight_template_id">运费模板ID</param>
        /// <param name="province_code">省编码</param>
        /// <param name="city_code">市编码</param>
        /// <param name="county_code">区编码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetFreight")]
        [CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
        public async Task<Response<FreightOutput>> GetFreight(int freight_template_id, string province_code, string city_code = "", string county_code = "")
        {
            Response<FreightOutput> result = new Response<FreightOutput>();
            result.code = 0;
            result.msg = "";
            try
            {
                if (freight_template_id == 0)
                {
                    result.msg = "运费模板不存在";
                    return result;
                }

                var freight = await db.gw_freight_distribution_areas
                     .Include(a => a.gw_freight_area_group)
                     .Where(a => a.template_id == freight_template_id && a.province_code == province_code)
                     .Select(a => new FreightOutput()
                     {
                         add_fee = a.gw_freight_area_group.add_fee,
                         add_number = a.gw_freight_area_group.add_number,
                         charge_type = (ChargeType)a.gw_freight_area_group.chargetype,
                         city_code = a.city_code,
                         county_code = a.county_code,
                         first_fee = a.gw_freight_area_group.first_fee,
                         first_number = a.gw_freight_area_group.first_number,
                         freight_template_id = a.template_id,
                         province_code = a.province_code,
                     })
                     .FirstOrDefaultAsync();

                result.code = 1;
                if (freight != null)
                {
                    freight.is_sale = true;
                    result.data = freight;

                }
                else
                {
                    result.data = new FreightOutput() { is_sale = false, };
                    result.msg = "所选地区暂时无货，非常抱歉！";
                }

            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

        /// <summary>
        /// 获得配置信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetSettings")]
        [CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
        public async Task<Response<SettingOutput>> GetSettings()
        {
            Response<SettingOutput> result = new Response<SettingOutput>();
            try
            {
                var settings = await db.gw_settings.ToListAsync();
                if (settings == null)
                {
                    result.code = 0;
                    result.msg = "获取失败！";
                    return result;
                }

                SettingOutput output = new SettingOutput()
                {
                    withdraw_service_fee_rate = settings.FirstOrDefault(s => s.name == "withdraw_service_fee_rate").value,
                    withdraw_max_amount = settings.FirstOrDefault(s => s.name == "withdraw_max_amount").value,
                    withdraw_min_amount = settings.FirstOrDefault(s => s.name == "withdraw_min_amount").value,
                };
                result.code = 1;
                result.data = output;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }
    }
}